package com.springcloud.study.oauth2.service;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: TODO
 * @Author dongguo
 * @Date 2020/4/23 17:45
 * @Version V1.0
 **/
public class DomainUserDetailsService implements UserDetailsService {

    private static List<Account> accountList = new ArrayList<>();

    static {
        String[] roles = new String[]{"aaa", "ccc", "bbb"};
        Account account1 = new Account(1, "guodong222", "guodong222", roles);
        Account account2 = new Account(2, "guodong333", "guodong333", roles);
        Account account4 = new Account(3, "guodong444", "guodong444", roles);
        Account account3 = new Account(4, "guodong555", "guodong555", roles);
        accountList.add(account1);
        accountList.add(account2);
        accountList.add(account3);
        accountList.add(account4);
    }



    /**
     * 根据用户名查找账户信息并返回用户信息实体
     * @param username 用户名
     * @return 用于身份认证的 UserDetails 用户信息实体
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountList.stream().filter(data -> data.getUserName().equals(username)).findFirst().get();
        if (account != null){
            return new User(account.getUserName(), account.getPassWord(), AuthorityUtils.createAuthorityList(account.getRoles()));
        }else {
            throw  new UsernameNotFoundException("用户["+username+"]不存在");
        }
    }


}
